from flask import Blueprint, request
from flask_jwt_extended import jwt_required, get_jwt_identity

from app.services.category_service import get_category_list_by_user_id, create_category_by_user, update_category_by_id, \
    delete_category_by_id
from app.utils.response import success, error

category_bp = Blueprint('categories', __name__, url_prefix='/categories')

"""
文章分类列表
"""
@category_bp.route('', methods=['GET'])
@jwt_required()
def get_category_list():
    user_id = get_jwt_identity()
    categories = get_category_list_by_user_id(user_id)
    if categories:
        return success(categories)
    else:
        return error()

"""
添加分类
"""
@category_bp.route('', methods=['POST'])
@jwt_required()
def create_category():
    data = request.get_json()
    user_id = get_jwt_identity()
    data['user_id'] = user_id
    category = create_category_by_user(data)
    if category:
        return success(category.to_dict())
    else:
        return error()

"""
编辑文章分类
"""
@category_bp.route('', methods=['PUT'])
@jwt_required()
def update_category():
    data = request.get_json()
    category = update_category_by_id(data)
    if category:
        return success(category.to_dict())
    else:
        return error()

"""
删除文章分类
"""
@category_bp.route('/<int:id>', methods=['DELETE'])
@jwt_required()
def delete_category(id):
    result = delete_category_by_id(id)
    if result:
        return success()
    else:
        return error()

